<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;

class Guanggao extends Controller
{
    public function index()
    {
        $data = Db::table('mh_guanggao')->select();
        return view('guanggao/index',[
            'data'=>$data
        ]);
    }

    public function add()
    {
        return view('guanggao/guanggaoadd');
    }

    public function do_add()
    {
        $data = $_POST;
        $file = request()->file('image');
        if($file){
            $info = $file->validate(['size'=>999999999,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'guanggao');
            if($info){
                $data['gg_img'] = $info->getSaveName();
            }else{
                echo $file->getError();
            }
        }

        $res = Db::table('mh_guanggao')->insert($data);
        if($res){
            $this->success('新增成功', 'admin/Guanggao/index');
        } else {
            $this->error('新增失败');
        }
    }

    public function delete($id)
    {
        $result = DB::table('mh_guanggao')->delete($id);
        if ($result > 0) {
            $info['status'] = true;
            $info['id'] = $id;
            $info['info'] = 'ID为' . $id . '的用户删除成功!';
        } else {
            $info['status'] = false;
            $info['id'] = $id;
            $info['info'] = 'ID为' . $id . '的用户删除失败!';
        }
        // JSON 返回
        return json($info);
    }

    public function edit($id)
    {
        $data = Db::table('mh_guanggao')->where(['id'=>$id])->find();
        return view('guanggao/guanggaoedit',[
            'data'=>$data,
        ]);
    }

    public function  do_edit()
    {
        $data = $_POST;
        $id = $data['id'];
        $file = request()->file('image');
        if($file){
            $info = $file->validate(['size'=>999999999,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'guanggao');
            if($info){
                $data['gg_img'] = $info->getSaveName();
            }else{
                echo $file->getError();
            }
        }
        unset($data['id']);
        $res = Db::table('mh_guanggao')->where(['id'=>$id])->update($data);
        if($res){
            $this->success('新增成功', 'admin/Guanggao/index');
        } else {
            $this->error('新增失败');
        }
    }

    public function gg_change($id)
    {
        $res = Db::table('mh_guanggao')->where(['gg_status'=>1])->update(['gg_status'=>2]);
        $ress = Db::table('mh_guanggao')->where(['id'=>$id])->update(['gg_status'=>1]);
        if($ress){
            $this->success('修改成功', 'admin/Guanggao/index');
        } else {
            $this->error('修改失败');
        }
    }


}
